package com.arvin.faceDetect.ui

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.SeekBar
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import com.arvin.faceDetect.R
import com.arvin.faceDetect.databinding.FragmentSystemSettingsBinding
import com.arvin.faceDetect.service.FloatingLogService

class SystemSettingsFragment : Fragment() {
    private var _binding: FragmentSystemSettingsBinding? = null
    private val binding get() = _binding!!

    private val overlayPermissionLauncher = registerForActivityResult(
        ActivityResultContracts.StartActivityForResult()
    ) {
        // 检查权限结果
        if (Settings.canDrawOverlays(requireContext())) {
            // 权限获取成功，启用调试模式和悬浮窗
            enableDebugModeAndFloatingButton()
            // 重新打开开关
            binding.switchDebugMode.isChecked = true
        } else {
            // 权限获取失败，保持开关关闭状态
            Toast.makeText(requireContext(), "需要悬浮窗权限才能启用调试模式", Toast.LENGTH_LONG)
                .show()
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentSystemSettingsBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        setupToolbar()
        setupSystemSettings()
        loadSettings()
        setupDeviceInfo()
        loadVersion()
        setupLogManagement()
    }

    private fun setupToolbar() {
        binding.toolbar.setNavigationOnClickListener {
            findNavController().navigateUp()
        }
    }

    private fun setupSystemSettings() {
        // 设置日志保存天数
        binding.seekBarLogRetention.setOnSeekBarChangeListener(object :
            SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                val days = progress + 1
                binding.tvLogRetentionValue.text = "保存天数：${days}天"
                if (fromUser) {
                    saveLogRetentionSetting(days)
                }
            }

            override fun onStartTrackingTouch(seekBar: SeekBar?) {}
            override fun onStopTrackingTouch(seekBar: SeekBar?) {}
        })

        // 设置调试模式开关
        binding.switchDebugMode.setOnCheckedChangeListener { _, isChecked ->
            if (isChecked) {
                // 检查悬浮窗权限
                if (!Settings.canDrawOverlays(requireContext())) {
                    // 请求悬浮窗权限
                    requestOverlayPermission()
                    // 先关闭开关，等待权限申请结果
                    binding.switchDebugMode.isChecked = false
                } else {
                    // 已有权限，启用调试模式和悬浮窗
                    enableDebugModeAndFloatingButton()
                }
            } else {
                // 关闭调试模式和悬浮窗
                disableDebugModeAndFloatingButton()
            }
        }
    }

    private fun requestOverlayPermission() {
        val intent = Intent(
            Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
            Uri.parse("package:${requireContext().packageName}")
        )
        overlayPermissionLauncher.launch(intent)
    }

    private fun enableDebugModeAndFloatingButton() {
        // 保存设置
        saveDebugModeSetting(true)
        saveShowFloatingButtonSetting(true)

        // 更新UI
        binding.switchDebugMode.isChecked = true

        // 启动悬浮窗服务
        val intent = Intent(requireContext(), FloatingLogService::class.java)
        requireContext().startService(intent)

        Toast.makeText(requireContext(), "调试模式已启用", Toast.LENGTH_SHORT).show()
    }

    private fun disableDebugModeAndFloatingButton() {
        // 保存设置
        saveDebugModeSetting(false)
        saveShowFloatingButtonSetting(false)

        // 更新UI
        binding.switchDebugMode.isChecked = false

        // 停止悬浮窗服务
        val intent = Intent(requireContext(), FloatingLogService::class.java)
        requireContext().stopService(intent)

        Toast.makeText(requireContext(), "调试模式已关闭", Toast.LENGTH_SHORT).show()
    }

    private fun loadSettings() {
        val prefs =
            requireContext().getSharedPreferences("face_detect_settings", Context.MODE_PRIVATE)

        // 加载系统设置
        val logRetention = prefs.getInt("log_retention_days", 7)
        binding.seekBarLogRetention.progress = logRetention - 1
        binding.tvLogRetentionValue.text = "保存天数：${logRetention}天"

        // 检查调试模式状态
        val isDebugMode = prefs.getBoolean("debug_mode", false)
        if (isDebugMode && !Settings.canDrawOverlays(requireContext())) {
            // 如果之前开启了调试模式但现在没有悬浮窗权限，则关闭调试模式
            disableDebugModeAndFloatingButton()
        } else {
            binding.switchDebugMode.isChecked = isDebugMode
        }
    }

    private fun setupDeviceInfo() {
        val deviceInfo = StringBuilder()
        deviceInfo.append("设备型号：${Build.MODEL}\n")
        deviceInfo.append("Android版本：${Build.VERSION.RELEASE}\n")
        deviceInfo.append("系统版本号：${Build.VERSION.SDK_INT}\n")
        deviceInfo.append("制造商：${Build.MANUFACTURER}")
        binding.tvDeviceInfo.text = deviceInfo.toString()
    }

    private fun loadVersion() {
        try {
            val packageInfo =
                requireContext().packageManager.getPackageInfo(requireContext().packageName, 0)
            binding.tvVersion.text = "v${packageInfo.versionName}"
        } catch (e: Exception) {
            binding.tvVersion.text = "v1.0.0"
        }
    }

    private fun saveLogRetentionSetting(days: Int) {
        requireContext().getSharedPreferences("face_detect_settings", Context.MODE_PRIVATE)
            .edit()
            .putInt("log_retention_days", days)
            .apply()
    }

    private fun saveDebugModeSetting(enabled: Boolean) {
        requireContext().getSharedPreferences("face_detect_settings", Context.MODE_PRIVATE)
            .edit()
            .putBoolean("debug_mode", enabled)
            .apply()
    }

    private fun saveShowFloatingButtonSetting(enabled: Boolean) {
        requireContext().getSharedPreferences("face_detect_settings", Context.MODE_PRIVATE)
            .edit()
            .putBoolean("show_floating_button", enabled)
            .apply()
    }

    private fun setupLogManagement() {
        binding.layoutLogManagement.setOnClickListener {
            findNavController().navigate(R.id.action_systemSettingsFragment_to_logManagementFragment)
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
} 